<?php

namespace Index\Controller;

use Think\Controller;
use Index\ViewModel;
use Index\Service;

/**
 * 说明：管理员管理控制器
 * 作者：王楠
 * 创建日期：2017-09-11
 */
class AdminController extends CommonController {

    /**
     * 管理员列表
     */
    public function adminlist() {
	$state_enum = getenumbykey('admin_state');
	$state_arr = getarrbyenum($state_enum);
	$appname_arr = $this->getapplist();
	$appname_enum = $this->getenumbyarr($appname_arr);
	$app_code = $this->app_code;
	$admin_role_level = $this->admin_role_level;
	$map['state'] = array('neq', 3);
	$map['role_id'] = array('gt', 0);
	$map['role_level'] = array('gt', (int)$admin_role_level);
	$state = trim(I('ddlstate'));
	$begintime = trim(I('txtbegintime'));
	$endtime = trim(I('txtendtime'));
	$keyword = trim(I('txtkeyword'));
	$appcode = trim(I('ddlapp', '0'));
	if (!empty($app_code)) {
	    $map['app_flag'] = $app_code;
	} else {
	    if (!empty($appcode)) {
		$map['app_flag'] = $appcode;
	    } else if ($appcode == '') {
		$map['app_flag'] = array(array('exp', 'is null'), array('eq', ''), 'or');
	    }
	}
	if (!empty($state)) {
	    $map['state'] = $state;
	}
	if (!empty($begintime) || !empty($endtime)) {
	    if (!empty($begintime) && !empty($endtime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), strtotime($endtime) + 60));
	    } else if (!empty($begintime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), time() + 60));
	    } else if (!empty($endtime)) {
		$map['ctime'] = array('between', array(0, strtotime($endtime) + 60));
	    }
	}
	if (!empty($keyword)) {
	    $where['chat_admin.username'] = array('like', '%' . $keyword . '%');
	    $where['chat_admin.name'] = array('like', '%' . $keyword . '%');
	    $where['chat_admin.phone'] = array('like', '%' . $keyword . '%');
	    $where['chat_adminrole.name'] = array('like', '%' . $keyword . '%');
	    $where['_logic'] = 'or';
	    $map['_complex'] = $where;
	}
	$viewModel = new ViewModel\AdminViewModel();
	$total = $viewModel->where($map)->count();
	$row = '10';
	$page = new Service\PageService($total, $row);
	$fpage = $page->fpage();
	$data = $viewModel->where($map)->limit($page->listfirst, $page->listRows)->order('ctime desc')->select();
	foreach ($data as $key => $value) {
	    $data[$key]['appname'] = $appname_enum[$data[$key]['app_flag']];
	    $data[$key]['state_text'] = $state_enum[$data[$key]['state']];
	    $data[$key]['ctime'] = date('Y-m-d H:i', $data[$key]['ctime']);
	}
	$search = array('appsel' => $appcode, 'statesel' => $state, 'keyword' => $keyword, 'begintime' => $begintime, 'endtime' => $endtime);
	$this->assign(array(
	    'data' => $data,
	    'fpage' => $fpage,
	    'total' => $total,
	    'statearr' => $state_arr,
	    'search' => $search,
	    'app_code' => $app_code,
	    'apparr' => $this->getapplist()
	));
	$this->display();
    }

    /**
     * 管理员编辑（添加，修改）
     */
    public function adminadd() {
	$state_enum = getenumbykey('admin_state');
	$admin_role_level = $this->admin_role_level;
	$app_code = $this->app_code;
	$model = M('chat_adminrole');
	if (!empty($app_code)) {
	    $map['app_flag'] = $app_code;
	} else {
	    $map['app_flag'] = array(array('exp', 'is null'), array('eq', ''), 'or');
	}
	$map['state'] = '1';
	$map['level'] = array('gt', $admin_role_level);
	$data = $model->where($map)->order('ctime desc')->select();
	$id = I('id');
	$columnname = '添加管理员';
	$btnname = '添加';
	if (!empty($id)) {
	    $columnname = '修改管理员';
	    $btnname = '修改';
	    $adminModel = M('chat_admin');
	    $data_admin = $adminModel->where(array('id' => $id))->find();
	    $appcode = $data_admin['app_flag'];
	    $role_id = $data_admin['role_id'];
	    $username = $data_admin['username'];
	    $name = $data_admin['name'];
	    $phone = $data_admin['phone'];
	    $state = $state_enum[$data_admin['state']];
	    $ctime = date('Y-m-d H:i', $data_admin['ctime']);
	    foreach ($data as $key => $value) {
		if ($role_id == $value['id']) {
		    $data[$key]['role_selected'] = "selected='selected'";
		}
	    }
	}
	$this->assign(array(
	    'id' => $id,
	    'appcode' => $appcode,
	    'role_id' => $role_id,
	    'username' => $username,
            'fxcode' => $data_admin['fxcode'],
	    'name' => $name,
	    'phone' => $phone,
	    'state' => $state,
	    'ctime' => $ctime,
	    'apparr' => $this->getapplist(),

	));
	$this->assign('columnname', $columnname);
	$this->assign('btnname', $btnname);
	$this->assign('data', $data);
	$this->assign('fxcode', $this->getFxCode());
	$this->display();
    }

    /**
     * 管理员编辑（添加，修改）提交
     *
     * @todo --添加的时候关联-code，同时userinfo添加code
     * @return type
     */
    public function adminaddsubmit() {
	if (!IS_POST) {
	    $this->error('非法访问！');
	}
	$app_code = $this->app_code;
	if (empty($app_code)) {
	    $app_code = I('app_code');
	}
	$admin_id = $this->admin_id;
	$id = I('id');
	$username = trim(I('username'));
	$pwdreset = trim(I('pwdreset'));
	$roleid = trim(I('roleid'));
	$name = trim(I('name'));
	$phone = trim(I('phone'));
	$fxcode = trim(I('fxcode'));
	if (empty($username)) {
	    $response = array('ret' => '1002', 'code' => '管理员账号不能为空！');
	    return $this->ajaxReturn($response, 'json');
	}
	if (empty($roleid)) {
	    $response = array('ret' => '1002', 'code' => '管理员角色不能为空！');
	    return $this->ajaxReturn($response, 'json');
	}
	if (!empty($phone) && !preg_match("/1[34578]{1}\d{9}$/", $phone)) {
	    $response = array('ret' => '1002', 'code' => '手机号码格式不正确！');
	    return $this->ajaxReturn($response, 'json');
	}
	if (!empty($app_code)) {
	    $map['app_flag'] = $app_code;
	} else {
	    $map['app_flag'] = array(array('exp', 'is null'), array('eq', ''), 'or');
	}
	$map['state'] = array('neq', '3');
	$map['username'] = $username;
	if (!empty($id)) {
	    $map['id'] = array('neq', $id);
	}
	$model = M('chat_admin');
	if ($model->where($map)->count()) {
	    $response = array('ret' => '1002', 'code' => '对不起，该账号已存在！');
	    return $this->ajaxReturn($response, 'json');
	}
	$data['username'] = $username;
	if (!empty($pwdreset)) {
	    $data['password'] = md5('123456');
	}
	$data['role_id'] = $roleid;
	$data['name'] = $name;
	$data['phone'] = $phone;
	$data['fxcode'] = $fxcode;
	if (empty($id)) {
	    $data['admin_id'] = $admin_id;
	    $data['password'] = md5('123456');
	    $data['state'] = '1';
	    $data['ctime'] = time();
	    if (!empty($app_code)) {
		$data['app_flag'] = $app_code;
	    }
	}
	if (!empty($id)) {
	    if ($model->where(array('id' => $id))->save($data)) {
		$response = array('ret' => '1001', 'code' => '修改成功！');
	    } else {
		$response = array('ret' => '1001', 'code' => '修改成功！');
	    }
	} else {
	    if ($model->add($data)) {
		$response = array('ret' => '1001', 'code' => '添加成功！');
	    } else {
		$response = array('ret' => '1002', 'code' => '添加失败！');
	    }
	}
        //关联用户的fxcode
        $modele_user =  M('chat_userinfo');
        $user_info = $modele_user->where(['user_phone'=>$username])->find();
        if (!empty($user_info)){
            $modele_user->where(['user_phone'=>$phone])->save(['fxcode'=>$fxcode]);
        }

        return $this->ajaxReturn($response, 'json');
    }

    /**
     * 删除管理员提交
     * @return type
     */
    public function deletesubmit() {
	$id = I('id');
	if (!empty($id)) {
	    $model = M('chat_admin');
	    $data = $model->where(array('id' => $id))->find();
	    if ($data) {
		$data['state'] = '3';
		$result = $model->save($data);
		if ($result) {
		    return $this->ajaxReturn(array('ret' => '1001', 'code' => '删除成功！'));
		} else {
		    return $this->ajaxReturn(array('ret' => '1002', 'code' => '删除失败！'));
		}
	    } else {
		return $this->ajaxReturn(array('ret' => '1002', 'code' => '对不起，该管理员可能已被删除！'));
	    }
	}
    }

    /**
     * 锁定管理员提交
     * @return type
     */
    public function locksubmit() {
	$id = I('id');
	if (!empty($id)) {
	    $model = M('chat_admin');
	    $data = $model->where(array('id' => $id))->find();
	    if ($data) {
		$data['state'] = '2';
		$result = $model->save($data);
		if ($result) {
		    return $this->ajaxReturn(array('ret' => '1001', 'code' => '锁定成功！'));
		} else {
		    return $this->ajaxReturn(array('ret' => '1002', 'code' => '锁定失败！'));
		}
	    } else {
		return $this->ajaxReturn(array('ret' => '1002', 'code' => '对不起，该管理员可能已被删除！'));
	    }
	}
    }

    /**
     * 解锁管理员提交
     * @return type
     */
    public function unlocksubmit() {
	$id = I('id');
	if (!empty($id)) {
	    $model = M('chat_admin');
	    $data = $model->where(array('id' => $id))->find();
	    if ($data) {
		$data['state'] = '1';
		$result = $model->save($data);
		if ($result) {
		    return $this->ajaxReturn(array('ret' => '1001', 'code' => '解锁成功！'));
		} else {
		    return $this->ajaxReturn(array('ret' => '1002', 'code' => '解锁失败！'));
		}
	    } else {
		return $this->ajaxReturn(array('ret' => '1002', 'code' => '对不起，该管理员可能已被删除！'));
	    }
	}
    }

}
